import axios, { AxiosError, AxiosRequestConfig } from "axios";

export const useRequest = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  try {
    const res = await axios.request<T>({
      ...config,
      url
    });
    // todo: 此处记录日志
    return res.data;
  } catch (e) {
    if (e instanceof AxiosError) {
      console.error(`请求基础地址：${e.config?.baseURL}
请求地址：${e.config?.url}
请求头：${e.config?.headers}
请求体：${e.config?.data}

响应头：${e.response?.headers}
响应体：${e.response?.data}

响应码：${e.code}
响应状态：${e.status}
响应消息：${e.message}`);
    }
    throw e;
  }
};

export const useRequestText = async (url: string, config?: AxiosRequestConfig): Promise<string> => {
  return await useRequest<string>(url, {
    ...config,
    responseType: "text"
  });
};

export const useGetText = async (url: string, params?: Record<string, any>): Promise<string> => {
  return useRequest<string>(url, {
    params,
    method: "GET",
    responseType: "text"
  });
};
